package cj.web.admin.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.dao.GameDAO;
import cj.web.admin.dao.GameOrderDAO;
import cj.web.admin.dao.GradeDAO;
import cj.web.admin.dao.ReportCardOnlineDAO;
import cj.web.admin.dao.SchoolDAO;
import cj.web.admin.domain.Game;
import cj.web.admin.domain.ReportCard;
import cj.web.admin.domain.ReportCardOnline;
import cj.web.constants.MemuEnum;
import cj.web.constants.PayStatusEnum;

@Path("/reportCardOnline")
public class ReportCardOnlineController{

	private static Logger logger = Logger.getLogger(ReportCardOnlineController.class.getName());
	
	@Autowired
	private ReportCardOnlineDAO reportCardDao;
	@Autowired
	private GameDAO gameDao;
	@Autowired
	private SchoolDAO schoolDao;
	@Autowired
	private GradeDAO gradeDao;
	@Autowired
	private GameOrderDAO gameOrderDao;
	
	@Get("show")
	public String show(Model model,ReportCard reportCard) {
	
		//MemuEnum
        model.add("MemuEnum",MemuEnum.wlzwcjgl);
        List<Game> objs = gameDao.queryAll();
		model.add("gameObjs", objs);
		List<Map> grades = gradeDao.asGradeEnum();
		model.add("Grade", grades);
		List<Map> schools = schoolDao.asSchoolEnum();
		model.add("School", schools);
		model.add("PayStatus", EnumSet.allOf(PayStatusEnum.class));
		return "/views/game/reportCardOnlineList.vm";
	}

	@Post("getList")
	public String queryList(ReportCardOnline reportCard) {
	
		JSONObject jo = new JSONObject();
		
		List<ReportCardOnline> objs = reportCardDao.query(reportCard);
		for(ReportCardOnline obj:objs){
			obj.setPayStatusName(obj.getPayStatus()==null?PayStatusEnum.WFK.getName():PayStatusEnum.getName(obj.getPayStatus()));
		}
		
		int size = reportCardDao.querysize(reportCard);
		jo.put("data", objs);
		jo.put("draw", reportCard.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id){
		reportCardDao.deleteById(id);
		return "r:show";
	}
	
	@Get("updatePayStatusById")
	public String updatePayStatusById(Model model,@Param("id") int id){
		reportCardDao.updatePayStatusById(id);
		return "r:show";
	}
	
	@Get("showImportExcel")
	public String showImportExcel(Model model,ReportCardOnline reportCard) {
	
		//MemuEnum
        model.add("MemuEnum",MemuEnum.jcimport);
        List<Game> objs = gameDao.queryAll();
		model.add("gameObjs", objs);
		return "/views/game/reportCardImportList.vm";
	}
	
	//Excel头
	private final String[] headers = { "参赛证号", "奖次", "考生姓名", "指导老师", "考生学校", "考生年级", "家长姓名", "家长联系方式", "路径", "区域", "题号"};
	
	@Post("xlsInput")
	public String xlsInput(Model model, @Param("xlsFile")MultipartFile xls,@Param("gameId")String gameId) throws FileNotFoundException, IOException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
		if (xls != null && !xls.isEmpty()) {
			String orgName = xls.getOriginalFilename();
			String ext =  ReturnUUID.getFileExt(orgName);
			if( ext != null && ext.equals(".xls")){
            	//文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//文件名
                String fileName =  ReturnUUID.getName(orgName);
                //转存文件  
                File tmpXls = new File(path+"/"+fileName);
                xls.transferTo(tmpXls);
                //处理excel文件
                jo = operateXls(tmpXls,Integer.parseInt(gameId));
			}
			else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2); //文件不是excel
			}
        }
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_1);     //文件不存在
		}

		return "@" + jo.toString();
	}
	
	/**
	 * 导入Excel方法
	 * @param tmpXls
	 * @param gameId
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private JSONObject operateXls(File tmpXls,int gameId) throws FileNotFoundException, IOException {
		JSONObject jo = new JSONObject();
		//获取工作簿
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(tmpXls));
		//获取sheet页
		HSSFSheet sheet = workbook.getSheetAt(0);
		
		//获取标题行
		HSSFRow titles = sheet.getRow(0);
		if(titles.getPhysicalNumberOfCells() != headers.length){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_3);     //请按照订单导出的Excel导入数据
			return jo;
		}
		String wrongTitles = "",rightTitles="";
		for( int col= 0; col < titles.getPhysicalNumberOfCells(); col++ ){
			String title = titles.getCell(col).getStringCellValue();
			if(!title.equals(headers[col])){
				wrongTitles += title + " ";
				rightTitles += headers[col] + " ";
			}
		}
		if(!"".equals(wrongTitles)){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_4);     //导入表表头错误
			jo.put("wrongTitles", wrongTitles);
			jo.put("rightTitles", rightTitles);
			return jo;
		}
		
		/*------判断订单中数据正确性 START------*/
		int lastRowNum = sheet.getLastRowNum();
		
		String codes[] = returnExcelCell(sheet, lastRowNum, 0);
		String levels[] = returnExcelCell(sheet, lastRowNum, 1);
		String names[] = returnExcelCell(sheet, lastRowNum, 2);
		String teachers[] = returnExcelCell(sheet, lastRowNum, 3);
		String schools[] = returnExcelCell(sheet, lastRowNum, 4);
		String grades[] = returnExcelCell(sheet, lastRowNum, 5);
		String parentNames[] = returnExcelCell(sheet, lastRowNum, 6);
		String parentPhones[] = returnExcelCell(sheet, lastRowNum, 7);
		String paths[] = returnExcelCell(sheet, lastRowNum, 8);
		
		String area[] = returnExcelCell(sheet, lastRowNum, 9);
		String th[] = returnExcelCell(sheet, lastRowNum, 10);
		/*------判断订单中数据正确性 END------*/
		
		//更新状态
		for(int i = 0; i < codes.length; i++){
			ReportCardOnline reportCard = new ReportCardOnline();
			reportCard.setCode(codes[i]);
			reportCard.setLevel(levels[i]);
			reportCard.setPath(paths[i]);
			reportCard.setTh(th[i]);
			
			List<Map> reps = gameOrderDao.queryStatusByCode(codes[i],gameId);
			
			if(reps!=null && reps.size()>0){
				if(reps.get(0).get("name")!=null && !"".equals(reps.get(0).get("name").toString())){
					reportCard.setName(reps.get(0).get("name").toString());
				}else{
					reportCard.setName(names[i]);
				}
				
				if(reps.get(0).get("teacher")!=null && !"".equals(reps.get(0).get("teacher").toString())){
					reportCard.setTeacher(reps.get(0).get("teacher").toString());
				}else{
					reportCard.setTeacher(teachers[i]);
				}
				
				if(reps.get(0).get("school")!=null && !"".equals(reps.get(0).get("school").toString())){
					reportCard.setSchool(reps.get(0).get("school").toString());
				}else{
					reportCard.setSchool(schools[i]);
				}
				
				if(reps.get(0).get("grade")!=null && !"".equals(reps.get(0).get("grade").toString())){
					reportCard.setGrade(reps.get(0).get("grade").toString());
				}else{
					reportCard.setGrade(grades[i]);
				}
				
				if(reps.get(0).get("parentName").toString()!=null && !"".equals(reps.get(0).get("parentName").toString())){
					reportCard.setParentName(reps.get(0).get("parentName").toString());
				}else{
					reportCard.setParentName(parentNames[i]);
				}
				
				if(reps.get(0).get("parentPhone").toString()!=null && !"".equals(reps.get(0).get("parentPhone").toString())){
					reportCard.setParentPhone(reps.get(0).get("parentPhone").toString());
				}else{
					reportCard.setParentPhone(parentPhones[i]);
				}
				
				if(reps.get(0).get("area").toString()!=null && !"".equals(reps.get(0).get("area").toString())){
					reportCard.setArea(reps.get(0).get("area").toString());
				}else{
					reportCard.setArea(area[i]);
				}
				
				reportCard.setPayStatus(Integer.parseInt(reps.get(0).get("status").toString()));
				reportCard.setGameId(gameId);
			}else{
				reportCard.setGameId(gameId);
				reportCard.setName(names[i]);
				reportCard.setTeacher(teachers[i]);
				reportCard.setSchool(schools[i]);
				reportCard.setGrade(grades[i]);
				reportCard.setParentName(parentNames[i]);
				reportCard.setParentPhone(parentPhones[i]);
				reportCard.setPayStatus(0);
				reportCard.setArea(area[i]);
			}
			
			//判断是不是存在
			int flag = reportCardDao.querySizeByCode(gameId,codes[i]);
			
			if(flag==0){
				//不存在插入
				reportCardDao.create(reportCard);
			}else{
				//存在更新
				reportCardDao.update(reportCard);
			}
		}
		
		return jo;
	}
	
	/**
	 * 返回excel单元格读取列表
	 * @param sheet			当前sheet
	 * @param lastRowNum	当前行号
	 * @param cellNum		当前列号
	 * @return
	 */
	private String[] returnExcelCell(HSSFSheet sheet,int lastRowNum,int cellNum){
		String array[] = new String[lastRowNum];
		for( int rowIndex = 1; rowIndex <= lastRowNum; rowIndex++ ){
			HSSFRow row = sheet.getRow(rowIndex);
			
			HSSFCell codeCell = row.getCell(cellNum);
			String code = "";
			if(codeCell != null){
				codeCell.setCellType(Cell.CELL_TYPE_STRING);
				code = codeCell.getStringCellValue();
			}
			if(code != null && !"".equals(code)){
				array[rowIndex-1] = code;
			}else{
				array[rowIndex-1] = "";
			}
			
		}
		return array;
	}
}